// 路由文件4个步骤
// 1.加载express
const path = require('path');
const db = require(path.join(__dirname, '../utils', 'db'));
const express = require('express');
const utility = require('utility');
// 2.创建路由对象
const router = express.Router();
// 3.把接口挂载到路由对象上
// ------------------  这里写接口  -----------------
// 获取用户信息接口
router.get('/userinfo', async(req, res) => {
    // console.log(req.user.id);
    let r = await db(
        'select id,username,nickname,email,user_pic from user where id=?',
        req.user.id
    );
    console.log(r);
    //[{id: 6,
    // username: 'liuqing',
    // nickname: null,
    // email: null,
    // user_pic: null}]
    if (r && r.length > 0) {
        res.send({ status: 0, message: '获取用户信息成功', data: r[0] });
    } else {
        res.send({ status: 1, message: '获取用户信息失败' });
    }
    // console.log(req.user);
});
// 更新密码接口
router.post('/updatepwd', async(req, res) => {
    let oldPwd = utility.md5(req.body.oldPwd);
    let newPwd = utility.md5(req.body.newPwd);
    if (oldPwd === newPwd) {
        return res.send({ status: 1, message: '新旧密码一致，请重新输入' });
    }
    let r1 = await db('select * from user where password=? and id=?', [
        oldPwd,
        req.user.id,
    ]);
    // console.log(r);
    if (r1 === undefined || r1.length === 0) {
        return res.send({ status: 1, message: '原密码输入错误' });
    }
    let r2 = await db('update user set password=? where id=?', [
        newPwd,
        req.user.id,
    ]);
    if (r2 && r2.affectedRows > 0) {
        res.send({ status: 0, message: '更新密码成功' });
    } else {
        res.send({ status: 1, message: '更新密码失败' });
    }
});
// 更换头像
router.post('/update/avatar', async(req, res) => {
    let r = await db('update user set user_pic=? where id=?', [
        req.body.avatar,
        req.user.id,
    ]);
    console.log(r);
    console.log(req.user.id);

    if (r && r.affectedRows > 0) {
        res.send({ status: 0, message: '更换头像成功' });
    } else {
        res.send({ status: 1, message: '更换头像失败' });
    }
});
// 更换用户信息
router.post('/userinfo', async(req, res) => {
    let r = await db('update user set ? where id=?', [req.body, req.user.id]);
    console.log(r);
    if (r && r.affectedRows > 0) {
        res.send({ status: 0, message: '更换信息成功' });
    } else {
        res.send({ status: 1, message: '更换信息失败' });
    }
});
// 4.导出路由对象

module.exports = router;